import time
import re
from basic.task import Task, TimeLine, TaskState
from basic.config import gcfg
from basic.workspace import Workspace
from basic.log import Log
from basic.spider import Spider
from datetime import datetime, timedelta


workspace = Workspace(gcfg.workspace, 'sigalarm')
logging = Log(workspace.path)
timeline = TimeLine()


class Meeting(object):
    def __init__(self, data):
        self.valid = False
        self.data = data
        self.start_time = None
        self.title = ''
        self.meeting_url = None
        self.content = ''

        self._parse()

    def __str__(self):
        return str([self.valid, self.start_time, self.title, self.meeting_url, self.content])

    def _parse(self):
        def _token_find(string, tokens):
            res = -1
            for token in tokens:
                tmp = string.find(token)
                if res == -1:
                    res = tmp
                elif tmp == -1 or res < tmp:
                    continue
                else:
                    res = tmp
            return res

        def _parse_time(string):
            string = string.strip()
            template = ['2030', '12', '28', '23', '59']
            numbers = re.findall(r'\d+', string)
            for i, n in enumerate(numbers):
                if i >= len(template):
                    break
                template[i] = n
            _time_string = ' '.join(template)
            try:
                return datetime.strptime(_time_string, '%Y %m %d %H %M')
            except:
                return None

        lines = self.data.splitlines()
        headline = lines[0]
        # ->->-> [ 2023/12/31 23:59 ] title | https://xxx
        s = _token_find(headline, ['[', '【'])
        e = _token_find(headline, [']', '】'])
        time_string = headline[s:e] if 0 <= s < e else None
        if time_string is None:
            return

        self.start_time = _parse_time(time_string)
        if self.start_time is None:
            return

        url_start = headline[e:].find('|') + e
        if url_start < e:
            url_start = len(headline)

        self.title = headline[e + 1:url_start].strip()
        self.meeting_url = headline[url_start + 1:].strip()

        self.content = ''
        for line in lines[1:]:
            if line.strip() == '':
                continue
            self.content += line
            self.content += '\n'

        self.valid = True


class Etherpad(object):
    def __init__(self, url):
        self.url = url
        self.export_url = url + '\export\\txt'
        self.data = Spider.get(self.export_url)

        self.analyze_ok = False
        self.next_meeting = None

        self.analyze()

    def analyze(self):
        blocks = self.data.split('->->-> ')
        now = datetime.now()
        pending_meetings = []
        for block in blocks:
            meeting = Meeting(block)
            if not meeting.valid:
                continue

            print('find a meeting.')
            self.analyze_ok = True
            if meeting.start_time > now:
                pending_meetings.append(meeting)

        if len(pending_meetings) == 0:
            print('no pending meeting.')
            return
        else:
            self.next_meeting = pending_meetings[0]

        for meeting in pending_meetings:
            if self.next_meeting.start_time > meeting.start_time:
                self.next_meeting = meeting

        print('next meeting: ', self.next_meeting)


    @staticmethod
    def alarm(now, last):
        if now.next_meeting is None:
            pass



def sig_server_loop():
    
    sig_list = db.sigs.get()
    last_data = {}
    for sig in sig_list:
        etherpad = Etherpad(sig.etherpad)
        
        if len(etherpad.pending_meetings) > 0:
            pass


def sigalarm_run():
    while True:
        print('sigalarm running')
        time.sleep(1)





if __name__ == '__main__':
    sigalarm_run()
    
    timeline.interval(1)

    main_task = Task('sig_server_loop', datetime.now(), sig_server_loop, None, 999999999999, timedelta(hours=4))
    timeline.register(main_task)


    timeline.run()